package com.woman.beautylive.presentation.ui.main.find.pengyouquan;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.R;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.main.find.PengYouQuanActivity;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.DongTaiDetailBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.DongTaiListBean;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.MyDongTaiBean;
import com.woman.beautylive.util.CameraPopupWindow;
import com.woman.beautylive.util.XImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * Created by admin on 2016/9/22.
 */
public class PublishActivity extends BaseActivity implements PublishInterFace, View.OnClickListener {
    TextView txt_publish;
    PublishPresenter publishPresenter;
    private int RESULT_REQUEST_CODE_GALLERY = 100;
    GridView img_grid;
    List<String> imgList = new ArrayList<>();
    public CameraPopupWindow mCameraPopupWindow;
    private String picture_name;
    private String fileName;
    private EditText edit_input;
    ImageView img_back;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish;
    }

    @Override
    protected void findViews(Bundle savedInstanceState) {
        img_back= (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(this);
        txt_publish = (TextView) findViewById(R.id.txt_publish);
        img_grid = (GridView) findViewById(R.id.img_grid);
        edit_input = (EditText) findViewById(R.id.edit_input);
        txt_publish.setOnClickListener(this);
        img_grid.setAdapter(new ImageAdapter(imgList));
        img_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imgList.size()) {
                    mCameraPopupWindow = new CameraPopupWindow(PublishActivity.this, PublishActivity.this);
                    mCameraPopupWindow.showAtLocation(
                            view,
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                }
            }
        });
    }

    private void getPictureFromGallery() {
//        Intent intent = new Intent();
//        intent.setType("image/*");
//        intent.setAction(Intent.ACTION_GET_CONTENT);
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        startActivityForResult(Intent.createChooser(intent, getString(R.string.photo_select)), RESULT_REQUEST_CODE_GALLERY);
        new PhotoSelectFragment(new PhotoSelect(),
                6 - imgList.size()).show(
                getSupportFragmentManager(), null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if()
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>我是图片的路径" + fileName);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            fileName=UploadImage.compress(fileName);
            imgList.add(fileName);
//            uploadImage(fileName);
            img_grid.setAdapter(new ImageAdapter(imgList));
        }
    }


    StringBuffer stringBuffer = new StringBuffer();
    int count = 0;//计数

    public void uploadImage(String path, final String content) {
        UploadImage.getInstance().execute(
                path, new UploadImage.OnUploadlistener() {

                    @Override
                    public void OnSuccess(String resultData) {
                        Toast.makeText(PublishActivity.this, resultData, 0).show();
                        count++;
                        System.out.println(resultData+"-------------->");
                        stringBuffer.append(resultData + ",");
                        if (count == imgList.size()) {
                            count=0;
                            Toast.makeText(PublishActivity.this, "图片上传成功", 0).show();
                            sendToServer(content);
                        }
                    }

                    @Override
                    public void OnError(String resultData) {
                        Toast.makeText(PublishActivity.this, resultData, 0).show();
                    }
                });


    }

    /**
     * 提交数据
     */
    private void sendToServer(String content) {
        count=0;
        publishPresenter.publish(LocalDataManager.getInstance().getLoginInfo().getToken(), content, stringBuffer.length() == 0 ? "" : stringBuffer.toString().substring(0, stringBuffer.length() - 1));
        System.out.println("最后上传的" + stringBuffer.toString());
    }

    @Override
    protected void init() {
        publishPresenter = new PublishPresenter(this);
    }

    @Override
    public void showPublishResult(PublishBean data) {
        if(data!=null) {
            Toast.makeText(this, data.getPid(), 0).show();
            sendMyBroadCast();
            finish();
        }else{
            Toast.makeText(this, "请求出错！请重试", 0).show();
        }
    }

    private void sendMyBroadCast() {
        //更新我的发布
        Intent intent=new Intent(WodeDongtaiActivity.REFRESHMYLIST);
        sendBroadcast(intent);

        //更新朋友圈
        Intent intentAll=new Intent(PengYouQuanActivity.REFRESHLIST);
        sendBroadcast(intentAll);

    }

    @Override
    public void showUpdatePublishResult(String data) {

    }

    @Override
    public void showDeletePublishResult(String data) {

    }

    @Override
    public void showdianzanResult(String data) {

    }

    @Override
    public void showDongtaiList(DongTaiListBean list) {

    }

    @Override
    public void showMyDongTaiList(List<MyDongTaiBean> list) {

    }

    @Override
    public void getDetailData(DongTaiDetailBean bean) {

    }

    @Override
    public void showHuiFuOneResult(PublishBean result) {

    }

    @Override
    public void showReplyDeleteResult(String result) {

    }

    @Override
    public void getReplyList(DongTaiListBean.DongTaiItem.ReplyList data) {

    }

    @Override
    public void getDianZanList(DongTaiListBean.DongTaiItem.ReplyList data) {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.open_camera) {
            openCamara();
            mCameraPopupWindow.dismiss();
        } else if (v.getId() == R.id.pick_image) {
            getPictureFromGallery();
            mCameraPopupWindow.dismiss();
        } else if (v.getId() == R.id.camera_cancel_tv) {
            mCameraPopupWindow.dismiss();
        } else if (v.getId() == R.id.txt_publish) {
            String content = edit_input.getText().toString();
            if (edit_input.getText().toString().equals("")) {
                Toast.makeText(this, "请输入内容", 0).show();
                return;
            }
            for (int i = 0; i < imgList.size(); i++) {
                uploadImage(imgList.get(i), content);
            }

        }else if(v.getId()==R.id.img_back){
            finish();
        }
    }


    /**
     * 打开相机
     */
    private void openCamara() {
        /**
         * 打开照相机
         */
        picture_name = android.text.format.DateFormat.format(
                "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
                + ".jpg";
        File file = new File("/sdcard/Image/");
        file.mkdirs();// 创建文件夹
        fileName = "/sdcard/Image/" + picture_name;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(fileName)));
        startActivityForResult(intent, 101);
    }

    class ImageAdapter extends BaseAdapter {

        List<String> imgList;

        public ImageAdapter(List<String> imgList) {
            this.imgList = imgList;
        }

        @Override
        public int getCount() {
            return imgList == null ? 1 : imgList.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return imgList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(BeautyLiveApplication.getContextInstance()).inflate(R.layout.item_fabiao_tiezi_image_select, null);
            ImageView img = (ImageView) convertView.findViewById(R.id.img);

            View del = convertView.findViewById(R.id.del);

            del.setTag(position);
            del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imgList.remove((int) v.getTag());
                    notifyDataSetChanged();
                }
            });
            if (position == imgList.size()) {
                img.setBackgroundResource(R.drawable.icon_addpic_focused);
                del.setVisibility(View.GONE);
            } else {
                XImageLoader.load("file://" + imgList.get(position), img);
                del.setVisibility(View.VISIBLE);
            }
            return convertView;
        }
    }

    class PhotoSelect implements PhotoSelectFragment.PhotoSelectListener {

        @Override
        public void onPhotoSelectFinish(List<String> paths) {

            for (String string : paths) {
                string=UploadImage.compress(string);//重新压缩过再上传
                imgList.add(string);
            }
            img_grid.setAdapter(new ImageAdapter(imgList));
        }

    }
}
